"""
Case Type   : 功能测试
Case Name   : 测试表及数据准备
Create At   : 2024/11/21
Owner       : peilinqian
Description :
    step1: 远程复制sql文件，并修改权限
    step2: 替换脚本中涉及的路径
    step3: 执行预置脚本
Expect      :
    step1: 远程复制sql文件，并修改权限 expect: 成功
    step2: 替换脚本中涉及的路径 expect: 替换成功
    step3: 执行预置脚本 expect: 执行成功
History     :
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro

logger = Logger()


class UstoreTearDown(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.basename(__file__)}:初始化----')
        self.constant = Constant()
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.pri_root = Node(node='PrimaryRoot')
        self.pri_dbuser = Node('PrimaryDbUser')
        self.com = Common()
        self.source_dir = os.path.join(macro.SCRIPTS_PATH, "ustore_data",
                                       "orsubquery_data")
        self.target_path = os.path.join(macro.DB_BACKUP_PATH, "orsubquery_data")
        self.pre_sql = 'Ustore_DQL_Orsubquery_Add_Setup.sql'

    def test_DataDel(self):
        text = '----step1: 远程复制sql文件，并修改权限 expect: 成功----'
        self.log.info(text)
        for file_item in os.listdir(self.source_dir):
            self.com.scp_file(self.pri_root, file_item, self.target_path,
                              source_dir=self.source_dir)
        chmod_cmd = f"chmod 777 -R {self.target_path};" \
                    f"ls -l {self.target_path}"
        self.log.info(chmod_cmd)
        chmod_result = self.pri_root.sh(chmod_cmd).result()
        self.log.info(chmod_result)

        text = '----step2: 替换脚本中涉及的路径 expect: 替换成功----'
        self.log.info(text)
        new_path_str = self.target_path.replace('/', '\/')
        msg = self.com.replace_file_content_by_sed(
            self.pri_dbuser, os.path.join(self.target_path, self.pre_sql),
            'script_path', new_path_str)
        self.log.info(msg)
        self.assertEqual('', msg, "执行失败" + text)

        text = '----step3: 执行预置脚本 expect: 执行成功----'
        self.log.info(text)
        shell = f'cd {self.target_path};' \
                f'source {macro.DB_ENV_PATH}; ' \
                f'gsql -d {self.pri_dbuser.db_name} ' \
                f'-f {self.pre_sql} '
        result = self.pri_dbuser.sh(shell).result()
        self.log.info(result)
        self.assertEqual(23, result.count('CREATE TABLE'), "执行失败" + text)
        self.assertEqual(23, result.count('COPY'), "执行失败" + text)

    def tearDown(self):
        logger.info(f'---- {os.path.basename(__file__)} 执行结束----')
